//
//  AddKucunVC.swift
//  com.yunshu.yunshuapp
//
//  Created by 周文杰 on 2018/1/16.
//  Copyright © 2018年 zwj. All rights reserved.
//

import UIKit
import BSImagePicker
import Photos

class AddKucunVC: UIViewController {

    let timeLabel = UILabel()
    let baojiaTV = UITextView()
    var imageUrls = ["","",""]
    
    let bgView = UIView(frame: CGRect(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
    let timePicker = UIDatePicker(frame: CGRect(x: 0, y: Const.SCREEN_HEIGHT-260, width: Const.SCREEN_WIDTH, height: 260))
    var model = XianhuoModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "添加库存表"
        self.view.backgroundColor = Const.WTM_WHITE_SMOKE
        self.view.addSubview(self.timeView());
        self.view.addSubview(self.baojiaView());
        self.view.addSubview(self.imagesView());
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确定", style: .plain, target: self, action: #selector(AddKucunVC.confirm))
    }
    
    func baojiaView() -> UIView {
        let bgView = UIView(frame: CGRect(x: 0, y: 50 + 64, width: Const.SCREEN_WIDTH, height: 200))
        bgView.backgroundColor = UIColor.white
        baojiaTV.frame = CGRect(x: 15, y: 0, width: Const.SCREEN_WIDTH - 30, height: 200);
        baojiaTV.font = UIFont.systemFont(ofSize: 14)
        bgView.addSubview(baojiaTV)
        return bgView
    }
    
    func imagesView() -> UIView {
        let view = UIView(frame: CGRect(x: 0, y: 250 + 64, width: Const.SCREEN_WIDTH, height: Const.SCREEN_WIDTH))
        let width = (Const.SCREEN_WIDTH - 40)/3
        let offset = Int(Const.SCREEN_WIDTH - width * 3) / 4
        for i in 0...2 {
            let x = offset + (Int(width) + offset)  * i
            let imageView = UIImageView(frame: CGRect(x: CGFloat(x), y: 10.0, width: width, height: width * 1.33))
            imageView.image = UIImage(named: "add_more_image.png")
            imageView.contentMode = .scaleAspectFill
            imageView.tag = i
            imageView.isUserInteractionEnabled = true
            imageView.layer.masksToBounds = true
            let tap = UITapGestureRecognizer.init(target: self, action: #selector(AddKucunVC.addImage(_:)))
            imageView.addGestureRecognizer(tap)
            view.addSubview(imageView)
        }
        return view
    }
    
    func timeView() -> UIView {
        let timeView = UIView(frame: CGRect(x: 15, y: 0 + 64, width: Const.SCREEN_WIDTH - 30, height: 50))
        let label1 = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 50))
        label1.text = "报价时间:"
        label1.font = UIFont.systemFont(ofSize: 13)
        timeView.addSubview(label1)
        
        timeLabel.frame = CGRect(x: 60, y: 0, width: Const.SCREEN_WIDTH - 100, height: 50)
        let now = Date.init()
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        timeLabel.text = formatter.string(from: now)
        timeLabel.font = UIFont.systemFont(ofSize: 13)
//        let tap = UITapGestureRecognizer(target: self, action: #selector(AddKucunVC.selectTime))
//        timeView.addGestureRecognizer(tap)
        timeView.addSubview(timeLabel)
        
        
//        let arrow = UIImageView(frame: CGRect(x: Const.SCREEN_WIDTH - 55, y: 10, width:  30, height: 30))
//        arrow.image = UIImage(named: "RightArrowB.png")
//        arrow.contentMode = .center
//        timeView.addSubview(arrow)
        
        return timeView
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func selectTime() {
        baojiaTV.resignFirstResponder()
        if timePicker.superview == nil {
            bgView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
            bgView.addSubview(timePicker)

            //        datePicker.dataSource = self;
            //        datePicker.delegate = self;
            timePicker.frame = CGRect.init(x:0, y:Const.SCREEN_HEIGHT - 216, width:Const.SCREEN_WIDTH, height:216);
            timePicker.backgroundColor = Const.WTM_LIGHTGRAY
            timePicker.datePickerMode = .dateAndTime
            timePicker.autoresizingMask = UIView.AutoresizingMask.flexibleWidth;
            //        datePicker.showsSelectionIndicator = true
            
            let bar = UIView(frame: CGRect(x: 0, y: Const.SCREEN_HEIGHT - 266, width: Const.SCREEN_WIDTH, height: 50))
            bar.backgroundColor = UIColor.white
            let cancel = UIButton(type: .roundedRect)
            cancel.frame = CGRect(x: 10, y: 5, width: 80, height: 40)
            cancel.setTitle("取消", for: .normal)
            cancel.addTarget(self, action: #selector(AddKucunVC.hideTimePicker), for: .touchUpInside)
            bar.addSubview(cancel)
            
            let ok = UIButton(type: .roundedRect)
            ok.frame = CGRect(x: Const.SCREEN_WIDTH - 90, y: 5, width: 80, height: 40)
            ok.setTitle("确定", for: .normal)
            ok.addTarget(self, action: #selector(AddKucunVC.corfirmTime), for: .touchUpInside)
            bar.addSubview(ok)
            bgView.addSubview(bar)
            bgView.addSubview(timePicker)
            self.view.addSubview(bgView)
        }
        let now = Date()
        timePicker.setDate(now, animated: false)
        self.navigationController?.view.addSubview(bgView)
    }
    
    @objc func hideTimePicker() {
        bgView.removeFromSuperview()
    }
    
    @objc func corfirmTime() {
        bgView.removeFromSuperview()
        let date = timePicker.date
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd HH:mm"
        let time = dateFormatter.string(from: date)
        timeLabel.text = time
        self.model.createtime = "\(Int(date.timeIntervalSince1970 * 1000))"
    }
    
    @objc func addImage(_ sender: UITapGestureRecognizer) {
        _ = baojiaTV.resignFirstResponder()
        let vc = ImagePickerController()
        vc.settings.list.cellsPerRow = { a, b in
                    return 4
                }
        vc.settings.selection.max = 1
        //        vc.settings.takePhotos = true
        presentImagePicker(vc, animated: true, select: {(asset) in
            DispatchQueue.main.async {
                vc.dismiss(animated: true, completion: {
                    let image = self.getUIImage(asset: asset)
                    self.pickImage(image , onView:sender.view as? UIImageView)
                    
                })
            }
        }, deselect: nil, cancel: nil, finish: nil)
        
    }
        
    func getUIImage(asset: PHAsset) -> UIImage? {

           var img: UIImage?
           let manager = PHImageManager.default()
           let options = PHImageRequestOptions()
           options.version = .original
           options.isSynchronous = true
           manager.requestImageData(for: asset, options: options) { data, _, _, _ in

               if let data = data {
                   img = UIImage(data: data)
               }
           }
           return img
       }

    func pickImage(_ image:UIImage?, onView:UIImageView?) {
        
        
//        btn.backgroundColor = Const.WTM_GRAY
//        btn2.backgroundColor = Const.WTM_GRAY
//        btn.isEnabled = false
//        btn2.isEnabled = false
        
        _ = NetworkManager.Upload(NetworkManager.UPLOAD_IMG2, image: image, ownerVC: self, callback: { (isSucess, resp) in
//            self.btn.backgroundColor = Const.WTM_GREEN
//            self.btn2.backgroundColor = Const.WTM_GREEN
//            self.btn.isEnabled = true
//            self.btn2.isEnabled = true
            if isSucess {
                let imgURL : String = resp.wtmDic["img"] as! String
                onView?.image = image
                if let index = onView?.tag {
                    self.imageUrls[index] = imgURL
                }
            }
        })
        
    }
    
    @objc func confirm() {
        
        guard let params = self.collectInfo() else{
            return
        }
        
        _ = NetworkManager.POST(NetworkManager.XIANHUO_UPDATE, params: params, ownerVC: self, callback: { (isSuccess, resp) in
            if(isSuccess){
                let alert = UIAlertController.init(title: "提示", message: "发布成功", preferredStyle: .alert)
                alert.addAction(UIAlertAction.init(title: "我知道了", style: .default, handler: { a in
                    self.navigationController?.popViewController(animated: true)
                }))
                DispatchQueue.main.async {
                    self.navigationController?.present(alert, animated: true, completion: nil)
                }
                
            }
        })
        
    }
    
    func collectInfo() ->[String:Any]? {
        let advert = self.timeLabel.text! + "发布：" + baojiaTV.text + "\n" + model.advert
        model.advert = advert
        var urls = [String]()
        for url in self.imageUrls {
            if url.count > 0 {
                if model.kucunpic.count == 0 {
                    model.kucunpic = url
                }else{
                    urls.append(url)
                }
            }
        }
        
        if urls.count > 0 {
            model.productpic = urls[0]
        }
        
        if urls.count > 1 {
            model.productpic1 = urls[1]
        }
        
        return model.serialize2()
    }
}
